package com.itheima.springbootmybatis.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootmybatis.mapper.ArticleMapper;
import com.itheima.springbootmybatis.pojo.FruitVegetables;
import com.itheima.springbootmybatis.pojo.PageBean;
import com.itheima.springbootmybatis.service.ArticleService;
import com.itheima.springbootmybatis.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

   @Override
    public void add(FruitVegetables fruitVegetables) {
       //补充属性值
       fruitVegetables.setCreateTime(LocalDateTime.now());
       fruitVegetables.setUpdateTime(LocalDateTime.now());

       Map<String,Object>map=ThreadLocalUtil.get();
       Integer userId=(Integer) map.get("id");
       fruitVegetables.setMerchantId(userId);
       articleMapper.add(fruitVegetables);
       articleMapper.updateNickname(userId);

    }

    @Override
    public PageBean<FruitVegetables> list(Integer pageNum, Integer pageSize,String origin,String fruitName) {
       //1.创建PageBean对象
        PageBean<FruitVegetables>pb=new PageBean<>();
        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);
        //3.调用mapper
        Map<String,Object>map=ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
        List<FruitVegetables>as= articleMapper.list(userId,origin,fruitName);
        //Page中提供了方法，可以获取PageHelper分页查询后，得到的记录条数和当前页数据
        Page<FruitVegetables>p=(Page<FruitVegetables>)as;
        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public FruitVegetables findById(Integer id) {
        FruitVegetables a=  articleMapper.findById(id);
        return a;
    }

    @Override
    public String update(FruitVegetables fruitVegetables) {
        fruitVegetables.setUpdateTime(LocalDateTime.now());
        Map<String,Object>map=ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
       String my=articleMapper.selectMy(userId,fruitVegetables);
       if (my!=null){
           articleMapper.update(userId,fruitVegetables);
           return "商品更新成功";

       }else {
           return null;
       }
    }



    @Override
    public String deleteById(Integer id) {
        Map<String,Object>map=ThreadLocalUtil.get();
        Integer userId=(Integer) map.get("id");
        String my=articleMapper.selectDeleteMy(userId,id);
        if (my!=null){
            articleMapper.deleteById(id);
            return "商品删除成功";

        }else {
            return null;
        }

    }


}
